package com.example.anni.zhuzhoujia.xiaowan;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.anni.zhuzhoujia.R;
import com.gitonway.lee.niftymodaldialogeffects.lib.Effectstype;
import com.gitonway.lee.niftymodaldialogeffects.lib.NiftyDialogBuilder;

import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Anni on 2016/6/5.
 */
public class UserFragment extends Fragment {
    private TextView tvLoginIn; //登录
    private ImageView ivHeader = null; //头像
    private TextView tvRevisePassword; //修改密码
    private TextView tvMySetup; //我的设置
    private TextView tvCancelLogin; //注销登录
    private LinearLayout linearBgColor;
    private Effectstype effect; //弹出对话框的动画类型
    private boolean isLogin; //是否登陆
    private TextView tvAttentionsNumber; //显示关注人数
    private TextView tvFansNumber;  //显示粉色人数
    private TextView tvAttentions;  //关注人数
    private TextView tvFans;  //粉丝人数
    private TextView tvReviseInformation;  //修改资料
    private TextView tvReadHistory;  //浏览历史
    private TextView tvMyCollection; //我的收藏
    private TextView tvMyComment; //我的评论

    //自定义的弹出框类
    SelectPicPopupWindow menuWindow;

    /*头像文件*/
    private static final String IMAGE_FILE_NAME = "temp_head_image.png";

    /*请求识别码*/
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;

    // 裁剪后图片的宽(X)和高(Y),480 X 480的正方形。
    private static int output_x = 480;
    private static int output_y = 480;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("onCreate", "onCreate");

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.user_fragment, null);
        return root;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.i("onViewCreated", "onViewCreated");
        tvLoginIn = (TextView) view.findViewById(R.id.tv_login_in);
        ivHeader = (ImageView) view.findViewById(R.id.iv_header);
        tvRevisePassword = (TextView) view.findViewById(R.id.tv_revise_password);
        tvMySetup = (TextView) view.findViewById(R.id.tv_my_setup);
        tvCancelLogin = (TextView) view.findViewById(R.id.tv_cancel_login);
        tvAttentionsNumber = (TextView) view.findViewById(R.id.tv_attentions_number);
        tvFansNumber = (TextView) view.findViewById(R.id.tv_fans_number);
        tvAttentions = (TextView) view.findViewById(R.id.tv_attentions);
        tvFans = (TextView) view.findViewById(R.id.tv_fans);
        linearBgColor = (LinearLayout) view.findViewById(R.id.liner_bg_color);
        tvReviseInformation = (TextView) view.findViewById(R.id.tv_revise_information);
        tvReadHistory = (TextView) view.findViewById(R.id.tv_read_history);
        tvMyCollection = (TextView) view.findViewById(R.id.tv_my_collection);
        tvMyComment = (TextView) view.findViewById(R.id.tv_my_comment);
    }

    @Override
    public void onResume() {
        super.onResume();
        LoginIn();
        isLogin();
        attentionsNum();
        getAttentionAndFansNum();
        fansNum();
        revisePassword();
        reviseMyInformation();
        showBottomPopupwindow();
        mySetup();
        cancelLogin();
        readHistory();
        myCollection();
        myComment();
    }

    //实现登录
    private void LoginIn() {
        tvLoginIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLogin) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(
                            R.animator.override_change_animator_in, R.animator.override_change_animator_out);
                }
            }
        });
    }

    //检测用户是否登录
    private void isLogin() {
        final RequestParams params1 =
                new RequestParams("http://tr.zzapi.gson.cn/api/user/isLogin");
        x.http().get(params1, new CallBackAdapter<String>() {
            @Override
            public void onSuccess(String s) {
                //Toast.makeText(getContext(), s, Toast.LENGTH_LONG).show();
                JSONObject object1 = JSON.parseObject(s);
                isLogin = object1.getBoolean("success");
                if (isLogin) {
                    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    String nickName = sp.getString("nickName", "");
                    String avatar = sp.getString("avatar", "");

                    /*String pathString =
                            Environment.getExternalStorageDirectory() + "/assets/images/avatar/" + IMAGE_FILE_NAME*/
                    ;
                    //ivHeader.setImageBitmap(toRoundBitmap(getDiskBitmap(pathString))); //头像
                    String attentions = sp.getString("attentions", "");
                    String fans = sp.getString("fans", "");
                    tvLoginIn.setText(nickName);  //昵称
                    tvAttentionsNumber.setText(attentions); //关注人数
                    Log.e("attentions-----", attentions);
                    tvFansNumber.setText(fans); //粉丝人数
                    linearBgColor.setBackgroundResource(R.mipmap.background);
                    ImageOptions options = new ImageOptions.Builder()
                            .setRadius(10)
                            .setSquare(true)
                            .setCircular(true)
                            .setFailureDrawableId(R.mipmap.header_whilte)
                            .build();
                    x.image().bind(ivHeader, "http://tr.zzapi.gson.cn/" + avatar, options);
                }
            }
        });
    }

    //关注人数
    private void attentionsNum() {
        tvAttentions.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (isLogin) {
                    Intent intent = new Intent(getActivity(), AttentionsRecyclerView.class);
                    startActivityForResult(intent, 0x004);
                } else {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //粉丝人数
    private void fansNum() {
        tvFans.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (isLogin) {
                    Intent intent = new Intent(getActivity(), FansNumRecyclerView.class);
                    startActivityForResult(intent, 0x009);
                } else {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //获取关注和粉丝人数
    public void getAttentionAndFansNum() {
        RequestParams params =
                new RequestParams("http://tr.zzapi.gson.cn/api/user/get/attentionAndFansNum");
        x.http().get(params, new CallBackAdapter<String>() {
            @Override
            public void onSuccess(String s) {
                JSONObject object = JSON.parseObject(s);
                //Log.e("object-----", object.toString());
                if (object.getBoolean("success")) {
                    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("attentions", object.getJSONObject("data").getString("attentions"));
                    editor.putString("fans", object.getJSONObject("data").getString("fans"));
                    editor.commit();
                    //设置关注人数
                    tvAttentionsNumber.setText(object.getJSONObject("data").getString("attentions"));
                    //设置粉丝人数
                    tvFansNumber.setText(object.getJSONObject("data").getString("fans"));
                }
            }
        });
    }

    //我的收藏
    private void myCollection() {
        tvMyCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLogin) {
                    Intent intent = new Intent(getActivity(), MyCollectionActivity.class);
                    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    String id = sp.getString("id", "");
                    intent.putExtra("uid", id);
                    startActivityForResult(intent, 0x010);
                } else {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //我的评论
    private void myComment() {
        tvMyComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLogin) {
                    Intent intent = new Intent(getActivity(), MyCommentActivity.class);
                    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    String id = sp.getString("id", "");
                    intent.putExtra("uid", id);
                    startActivityForResult(intent, 0x009);
                } else {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    //修改个人资料
    private void reviseMyInformation() {
        tvReviseInformation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLogin) {
                    Intent intent = new Intent(getActivity(), MyInformationActivity.class);
                    startActivityForResult(intent, 0x008);
                } else {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    //修改密码
    private void revisePassword() {
        tvRevisePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), RevisePasswordActivity.class);
                startActivityForResult(intent, 0x001);
            }
        });
    }

    //浏览历史
    private void readHistory() {
        tvReadHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLogin) {
                    Intent intent = new Intent(getActivity(), ReadHistoryActivity.class);
                    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    String id = sp.getString("id", "");
                    intent.putExtra("uid", id);
                    startActivity(intent);
                } else {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    //我的设置
    private void mySetup() {
        tvMySetup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MySetupActivity.class);
                startActivityForResult(intent, 0x001);
            }
        });
    }

    //注销登录
    private void cancelLogin() {
        tvCancelLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLogin) {
                    effect = Effectstype.Shake;
                    final NiftyDialogBuilder niftyDialog = NiftyDialogBuilder.getInstance(getContext());
                    niftyDialog
                            .withTitle("注销")
                            .withTitleColor("#ffffffff")
                            .withDividerColor("#11000000")
                            .withDialogColor("#FFE74C3C")
                            .withMessage("亲，您真的要注销吗？")
                            .withMessageColor("#ffffffff")
                            .withIcon(R.mipmap.cancel_login_image)
                            .isCancelableOnTouchOutside(true)
                            .withDuration(700)
                            .withEffect(effect)
                            .withButton1Text("确定")
                            .withButton2Text("取消")
                            .setCustomView(R.layout.cancel_content_login, getContext())
                            .setButton1Click(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    RequestParams params = new RequestParams("http://tr.zzapi.gson.cn/api/user/logout");
                                    x.http().get(params, new CallBackAdapter<String>() {
                                        @Override
                                        public void onSuccess(String s) {
                                            //Toast.makeText(getContext(),s, Toast.LENGTH_LONG).show();
                                            JSONObject object = JSON.parseObject(s);
                                            if (object.getBoolean("success")) {
                                                Toast.makeText(getContext(), object.getString("message"), Toast.LENGTH_LONG).show();
                                                tvLoginIn.setText("点击登录,体验更多");
                                                ivHeader.setImageResource(R.mipmap.header_whilte);
                                                tvAttentionsNumber.setText("0");
                                                tvFansNumber.setText("0");
                                                linearBgColor.setBackgroundColor(Color.parseColor("#ffff4444"));
                                                isLogin = false;
                                            } else {
                                                Toast.makeText(getContext(), object.getString("message"), Toast.LENGTH_LONG).show();
                                            }
                                            niftyDialog.dismiss();
                                        }
                                    });
                                }
                            })
                            .setButton2Click(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    niftyDialog.dismiss();
                                }
                            })
                            .show();
                } else {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //显示底部弹出Popupwindow
    private void showBottomPopupwindow() {
        ivHeader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLogin) {
                    //实例化SelectPicPopupWindow
                    menuWindow = new SelectPicPopupWindow(getActivity(), itemsOnClick);
                    //显示窗口
                    menuWindow.showAtLocation(getActivity().findViewById(R.id.main),
                            Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                } else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    Toast.makeText(getActivity(), "请先登录哦", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_pick_photo:
                    choseHeadImageFromGallery();
                    break;
                case R.id.btn_take_photo:
                    choseHeadImageFromCameraCapture();
                    break;
                default:
                    break;
            }
        }
    };

    // 从本地相册选取图片作为头像
    private void choseHeadImageFromGallery() {
        Intent intentFromGallery = new Intent();
        // 如果要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
        intentFromGallery.setType("image/*");
        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST);
    }

    // 启动手机相机拍摄照片作为头像
    private void choseHeadImageFromCameraCapture() {
        Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        // 判断存储卡是否可用，存储照片文件
        if (hasSdcard()) {
            intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                    .fromFile(new File(Environment
                            .getExternalStorageDirectory(), IMAGE_FILE_NAME)));
        }

        startActivityForResult(intentFromCapture, CODE_CAMERA_REQUEST);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode,
                                 Intent intent) {

        // 用户没有进行有效的设置操作，返回
        if (resultCode == getActivity().RESULT_CANCELED) {
            //Toast.makeText(getActivity(), "取消", Toast.LENGTH_LONG).show();
            return;
        }
        switch (requestCode) {
            case CODE_GALLERY_REQUEST:
                cropRawPhoto(intent.getData());
                break;

            case CODE_CAMERA_REQUEST:
                if (hasSdcard()) {
                    File tempFile = new File(
                            Environment.getExternalStorageDirectory(),
                            IMAGE_FILE_NAME);
                    cropRawPhoto(Uri.fromFile(tempFile));
                } else {
                    Toast.makeText(getActivity(), "没有SDCard!", Toast.LENGTH_LONG).show();
                }
                break;

            case CODE_RESULT_REQUEST:
                if (intent != null) {
                    try {
                        setImageToHeadView(intent);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }

        super.onActivityResult(requestCode, resultCode, intent);
    }

    //更换头像
    private void postImgData(final String pathString) {

        RequestParams params =
                new RequestParams("http://tr.zzapi.gson.cn/api/user/upload/avatar");
        params.setMultipart(true);
        params.addBodyParameter("fileItem", new File(pathString));
        x.http().post(params, new CallBackAdapter<String>() {
            @Override
            public void onSuccess(String s) {
                JSONObject object = JSON.parseObject(s);
                Log.e("fileItem", object.toString());
                if (object.getBoolean("success")) {
                    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("avatar", object.getString("data"));
                    editor.commit();
                    ivHeader.setImageBitmap(toRoundBitmap(getDiskBitmap(pathString)));
                    Toast.makeText(getActivity(), "更换成功", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getActivity(), "更换失败了，重新试一下吧", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    /**
     * 裁剪原始的图片
     */
    public void cropRawPhoto(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        // 如果要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
        intent.setDataAndType(uri, "image/*");

        // 设置裁剪
        intent.putExtra("crop", "true");

        // aspectX , aspectY :宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX , outputY : 裁剪图片宽高
        intent.putExtra("outputX", output_x);
        intent.putExtra("outputY", output_y);
        intent.putExtra("return-data", true);

        startActivityForResult(intent, CODE_RESULT_REQUEST);
    }

    /**
     * 提取保存裁剪之后的图片数据，并将Bitmap转换成文件
     */
    public File setImageToHeadView(Intent intent) throws IOException {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            String path = Environment.getExternalStorageDirectory().toString() + "/assets/images/avatar/";
            File dirFile = new File(path);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            File myIconFile = new File(path + IMAGE_FILE_NAME);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myIconFile));
            photo.compress(Bitmap.CompressFormat.PNG, 80, bos);
            bos.flush();
            bos.close();
            postImgData(Environment.getExternalStorageDirectory() +
                    "/assets/images/avatar/" + IMAGE_FILE_NAME);
            return myIconFile;
        }
        return null;
    }


    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        //MEDIA_MOUNTED 媒体安装
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            // 有存储的SDCard
            return true;
        } else {
            return false;
        }
    }

    /**
     * 转换图片为圆形
     *
     * @param bitmap 传入Bitmap对象
     * @return
     */
    public Bitmap toRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height) {
            roundPx = width / 2;
            top = 0;
            bottom = width;
            left = 0;
            right = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }

        Bitmap output = Bitmap.createBitmap(width,
                height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
        final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
        final RectF rectF = new RectF(dst);

        paint.setAntiAlias(true);

        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return output;
    }

    /**
     * 保存文件
     *
     * @param bm
     * @return
     * @throws IOException
     */
    /*public File saveFile(Bitmap bm) throws IOException {
        String path = Environment.getExternalStorageDirectory().toString() + "/w65/icon_bitmap/";
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File myIconFile = new File(path + IMAGE_FILE_NAME);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myIconFile));
        bm.compress(Bitmap.CompressFormat.PNG, 80, bos);
        bos.flush();
        bos.close();
        return myIconFile;
    }*/

    /**
     * 从本地获取图片
     *
     * @param pathString 文件路径
     * @return 图片
     */
    public Bitmap getDiskBitmap(String pathString) {
        Bitmap bitmap = null;
        try {
            File file = new File(pathString);
            if (file.exists()) {
                bitmap = BitmapFactory.decodeFile(pathString);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return bitmap;
    }
}



